package servlet;

import com.alibaba.fastjson.JSON;
import entity.Msg;
import entity.User;
import org.apache.commons.beanutils.BeanUtils;
import service.IUserService;
import service.imp.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jiuyuesheng
 * @date 2019/12/29  10:46
 */
public class UserServlet extends HttpServlet {
    private IUserService userService = new UserService();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String method = request.getParameter("method");
        if ("login".equals(method)) {
            doLogin(request, response);
        } else if ("register".equals(method)) {
            doRegister(request, response);
        } else if ("outLogin".equals(method)) {
            doOutLogin(request, response);
        } else if ("getInfo".equals(method)) {
            doGetInfo(request, response);
        }
    }

    private void doGetInfo(HttpServletRequest request, HttpServletResponse response) {
        String username = null;
        Cookie[] cookies = request.getCookies();
        Msg msg = new Msg();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())) {
                    username = cookie.getValue();
                }
            }
        }
        String responseString = null;
        if (username != null) {
            responseString = username;
            msg.setData(responseString);
        }

        try {
            response.getWriter().print(JSON.toJSONString(msg));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    private void doOutLogin(HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie("uid", "-1");
        Cookie cookie1 = new Cookie("username", "null");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        cookie1.setPath("/");
        cookie1.setMaxAge(0);
        response.addCookie(cookie1);
        //销毁session中的值
        HttpSession session = request.getSession();
        session.invalidate();
        String url = request.getContextPath();
        try {
            response.sendRedirect(url + "/index/Ymall.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doLogin(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        int rs = userService.doLogin(user);
        String responseString = "{\"msg\":404}";
        if (rs > 0) {
            responseString = "{\"msg\":200}";
            Cookie cookie = new Cookie("uid", Integer.toString(rs));
            Cookie cookie1 = new Cookie("username", username);
            cookie.setMaxAge(1000 * 3600 * 24);
            cookie.setPath("/");
            cookie1.setMaxAge(1000 * 3600 * 24);
            cookie1.setPath("/");
            response.addCookie(cookie);
            response.addCookie(cookie1);
        }
        try {
            response.getWriter().print(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void doRegister(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Map<String, String[]> parameters = new HashMap<>(request.getParameterMap());
        parameters.remove("method");
        User user = new User();
        try {
            BeanUtils.populate(user, parameters);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        String responseString = userService.doRegister(user);
        try {
            response.getWriter().print(responseString);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
